package cn.wolfcode.wolfcodemall.controller.admin;

import cn.wolfcode.wolfcodemall.domain.Category;
import cn.wolfcode.wolfcodemall.domain.Product;
import cn.wolfcode.wolfcodemall.domain.Property;
import cn.wolfcode.wolfcodemall.qo.PageQo;
import cn.wolfcode.wolfcodemall.qo.ProductQo;
import cn.wolfcode.wolfcodemall.service.CategoryService;
import cn.wolfcode.wolfcodemall.service.ProductService;
import cn.wolfcode.wolfcodemall.service.PropertyService;
import cn.wolfcode.wolfcodemall.vo.ProductVo;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 商品相关请求的控制器
 */
@Controller
@RequestMapping("/admin")
public class ProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private PropertyService propertyService;
    //商品列表页面
    @RequestMapping("/product")
    public String product(@ModelAttribute("qo") ProductQo qo, Model model){
        //条件查询商品信息
        PageInfo<Product> pageResult = productService.selectByCondition(qo);
//        //查询到商品信息
//        PageInfo<Product> pageResult = productService.selectByPage(qo);
        //将商品信息带到页面中显示
        model.addAttribute("pageResult",pageResult);

        //回显商品状态
        Integer[] productIsEnabled = qo.getProductIsEnabled();
        if(productIsEnabled != null && productIsEnabled.length == 2){
            model.addAttribute("productIsEnabled",2);
        }else if(productIsEnabled != null && productIsEnabled.length == 1){
            model.addAttribute("productIsEnabled",productIsEnabled[0]);
        }
        //查询所有分类信息
        List<Category> categoryList = categoryService.findAll();
        //将分类信息带到页面显示
        model.addAttribute("categoryList",categoryList);

        return "/admin/productManagePage";
    }
    //商品编辑页面
    @RequestMapping("/product/input")
    public String input(Model model,Integer productId){
        //查询所有分类信息
        List<Category> categoryList = categoryService.findAll();
        //将分类信息带到页面中显示
        model.addAttribute("categoryList",categoryList);

        if(productId != null){
            //根据商品的id查询商品信息
            Product product = productService.selectById(productId);
            //将商品信息带到页面回显
            model.addAttribute("product",product);
        }
        return "/admin/productinput";
    }

    //异步请求给定分类id下的属性信息
    @RequestMapping(value = "/property/{categoryId}",produces = "application/json;charset=utf-8")
    @ResponseBody   //告诉Springmvc当前返回字符串不是页面而是数据
    public String getProperty(@PathVariable Integer categoryId){
        //根据分类id查询到拥有的属性信息
        List<Property> propertyList = propertyService.findByCategoryId(categoryId);
        //将查询的属性信息返回
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("propertyList",propertyList);
        return jsonObject.toJSONString();
    }

    //商品图片上传
    @RequestMapping("/product/uploadProductImage")
    @ResponseBody
    public String uploadProductImage(MultipartFile file, String imageType, HttpServletRequest request){
        //获取上传文件的原始名
        String originalFilename = file.getOriginalFilename();
        //为上传的文件重新生成一个名字  aaa.txt
        String fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        //定义上传文件的存储位置
//        String filePath = "D:/upload/";
        String filePath = System.getProperty("user.dir") + "\\src\\main\\webapp\\upload\\";
        //定义上传文件存储目录
        String picPath;
        if(imageType.equals("single")){
            //概述图片
            picPath = "productSinglePic/";
        }else{
            //详情图片
            picPath = "productDetailsPic/";
        }
        //保证存储必须存在
        File picPathFile = new File(filePath + picPath);
        if(!picPathFile.exists()){
            picPathFile.mkdirs();
        }
        //上传文件
        //创建json对象，在对象封装要响应数据
        JSONObject jsonObject = new JSONObject();
        try {
            file.transferTo(new File(filePath + picPath + fileName));
            System.out.println("上传成功");
            //为上传的文件生成访问路径
            //http://localhost:80/upload/XXX/xxx.jpg
            String picUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/upload/" + picPath + fileName;
            System.out.println(picUrl);
            //向json对象中设置响应数据
            jsonObject.put("success",true);
            jsonObject.put("url",picUrl);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("上传失败");
            jsonObject.put("success",false);
        }
        return jsonObject.toJSONString();
    }

    //保存或更新
    @RequestMapping("/product/saveOrUpdate")
    public String saveOrUpdate(ProductVo vo){
        productService.saveOrUpdate(vo);
        return "redirect:/admin/product";
    }

}
